﻿using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace NetPay.WeChat.ProfitSharing
{
    /// <summary>
    /// 处理分账：请求分账/查询分账/请求分账回退/分账回退查询
    /// </summary>
    public class Order
    {

        /// <summary>
        /// 请求分账
        /// </summary>
        /// <param name="transaction_id">微信订单号</param>
        /// <param name="out_order_no">商户分账单号</param>
        /// <param name="receivers">分账接收方列表</param>
        /// <returns></returns>
        public static string AddProfitSharing(string transaction_id, string out_order_no, object receivers)
        {
            // 获取微信支付平台证书公钥
            var certificate = Certificates.GetCertificate();
            var public_key = certificate.Result;

            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            dic.Add("appid", Config.APPID);
            dic.Add("transaction_id", transaction_id);
            dic.Add("out_order_no", out_order_no);
            dic.Add("receivers", receivers);
            dic.Add("unfreeze_unsplit", true); // 是否解冻剩余未分资金
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            // 请求分账API
            var url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders";
            // 通过证书获取商户私钥序列号
            var path = System.Environment.CurrentDirectory + "/wwwroot/apiclient_cert.p12";
            X509Certificate2 cert = new X509Certificate2(path, Config.MCHID, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var serial_no = cert.SerialNumber;

            var result = RequestAddProfitSharingData(url, data, Config.MCHID, serial_no, public_key);

            return result;
        }

        /// <summary>
        /// 发送分账请求
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="data">数据对象</param>
        /// <param name="mchid">商户ID</param>
        /// <param name="serial_no">商户私钥序列号</param>
        /// <param name="public_key">微信平台公钥</param>
        /// <returns></returns>
        public static string RequestAddProfitSharingData(string url, string data, string mchid, string serial_no, string public_key)
        {
            var wechatpay_serial_no = Certificates.GetSerialNo().Result;
            byte[] byte_public_key = Encoding.UTF8.GetBytes(public_key);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
            request.Accept = "application/json";
            string authorization = Authorization.GetAuthorization(url, "POST", data, mchid, serial_no);
            request.Headers.Add("Authorization", authorization);
            // ！！！如果请求数据中存在敏感信息则需要在Headers添加Wechatpay-Serial，但“wechatpay_serial_no”不需要加密
            request.Headers.Add("Wechatpay-Serial", wechatpay_serial_no);

            byte[] paramJsonBytes;
            paramJsonBytes = Encoding.UTF8.GetBytes(data);
            request.ContentLength = paramJsonBytes.Length;

            Stream writer;
            try
            {
                writer = request.GetRequestStream();
            }
            catch (Exception)
            {
                writer = null;
            }
            writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
            writer.Close();

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            string text = reader.ReadToEnd();

            return text;
        }

        /// <summary>
        /// 查询分账结果
        /// </summary>
        /// <param name="out_order_no">路径参数:商户分账单号</param>
        /// <param name="transaction_id">查询参数:微信订单号</param>
        /// <returns></returns>
        public static string SearchProfitSharing(string out_order_no, string transaction_id)
        {
            // 通过证书获取商户私钥序列号
            var path = System.Environment.CurrentDirectory + "/wwwroot/apiclient_cert.p12";
            X509Certificate2 cert = new X509Certificate2(path, Config.MCHID, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var serial_no = cert.SerialNumber;

            var url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/" + out_order_no + "?transaction_id=" + transaction_id;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json;";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
            request.Accept = "application/json";
            string authorization = Authorization.GetAuthorization(url, "GET", Config.MCHID, serial_no);
            request.Headers.Add("Authorization", authorization);

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            string result = reader.ReadToEnd();

            return result;
        }

        /// <summary>
        /// 请求分账回退
        /// </summary>
        /// <param name="profitsharing_order_id"></param>
        /// <param name="out_order_no"></param>
        /// <param name="out_return_no"></param>
        /// <param name="return_mchid"></param>
        /// <param name="amount"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static string ProfitSharingReturn(string profitsharing_order_id, string out_order_no, string out_return_no, string return_mchid, int amount, string description)
        {
            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            dic.Add("order_id", profitsharing_order_id);
            dic.Add("out_order_no", out_order_no);
            dic.Add("out_return_no", out_return_no);
            dic.Add("return_mchid", return_mchid);
            dic.Add("amount", amount);
            dic.Add("description", description);
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            // 请求分账API
            var url = "https://api.mch.weixin.qq.com/v3/profitsharing/return-orders";
            // 通过证书获取商户私钥序列号
            var path = System.Environment.CurrentDirectory + "/wwwroot/apiclient_cert.p12";
            X509Certificate2 cert = new X509Certificate2(path, Config.MCHID, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var serial_no = cert.SerialNumber;

            var result = RequestProfitSharingReturnData(url, data, Config.MCHID, serial_no);

            return result;
        }

        /// <summary>
        /// 发送请求分账回退
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="data">数据对象</param>
        /// <param name="mchid">商户ID</param>
        /// <param name="serial_no">商户私钥序列号</param>
        /// <returns></returns>
        public static string RequestProfitSharingReturnData(string url, string data, string mchid, string serial_no)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
            request.Accept = "application/json";
            string authorization = Authorization.GetAuthorization(url, "POST", data, mchid, serial_no);
            request.Headers.Add("Authorization", authorization);

            byte[] paramJsonBytes;
            paramJsonBytes = Encoding.UTF8.GetBytes(data);
            request.ContentLength = paramJsonBytes.Length;

            Stream writer;
            try
            {
                writer = request.GetRequestStream();
            }
            catch (Exception)
            {
                writer = null;
            }
            writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
            writer.Close();

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            string text = reader.ReadToEnd();

            return text;
        }


    }
}